"use client";

import {Label} from "@/components/ui/label";
import {Input} from "@/components/ui/input";
import {Button} from "@/components/ui/button";
import {useState} from "react";


const WORKOUT_API_URL = "/api/workouts";

export default function WorkoutsForm() {
    const [message, setMessage] = useState("");
    const [error, setError] = useState("");

    async function handleSubmit(event) {
        // 整体思路：
        //     1、获取表单数据 转换成json格式 将数据发送给 nextjs /api/login
        //     2、/api/login 获取数据将数据发送给fastapi后端获取到access_token 并将 token设置到session中

        // 禁止页面地址跳转 会拼接form表单中的key和value到提交地址中/login?username=xxx&password=xxx
        event.preventDefault();
        // event.target <form>标签里的html内容
        // console.log(event, event.target);

        // 构建表单数据
        const formData = new FormData(event.target);
        // 从表单中获取数据对象
        const objectFromForm = Object.fromEntries(formData);
        // 将对象转换为json格式 {"username":"xxx","password":"xxx"}
        const jsonData = JSON.stringify(objectFromForm);
        // console.log(jsonData);
        // 构建请求信息：请求方式、请求头、请求体
        const requestOptions = {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: jsonData,
        }
        // 从next js 定义的 /api/login 地址请求数据
        const response = await fetch(WORKOUT_API_URL, requestOptions);
        const data = await response.json();
        // console.log(data);
        if (response.ok) {
            setMessage("Thank you for joining")
        } else {
            setError("There was an error with your request please try again");
        }
    }

    return (
        <form onSubmit={handleSubmit}>
            <div>{message && message}</div>
            <div>{error && error}</div>
            <div className="flex flex-col gap-6">
                <div className="grid gap-3">
                    <Label htmlFor="name">训练内容：</Label>
                    <Input
                        id="name"
                        type="text"
                        name="name"
                        placeholder="请输入训练内容"
                        required
                    />
                </div>
                <div className="flex flex-col gap-3">
                    <Button type="submit" className="w-full">
                        创建
                    </Button>
                </div>
            </div>
        </form>
    );
}
